/*
 * @Author       : 魏威 <1209562577@qq.com>
 * @Date         : 2022-02-23 11:27 周3
 * @Description  : 请求相关方法
 */

import { apiUrl } from "./const";
import qs from "qs";
import * as auth from "auth-provider";
import { useAuth } from "context/auth-context";

interface HttpConfig extends RequestInit {
  data?: any;
  token?: string;
}

export const http = async (
  endPoint: string,
  { data, token, headers, ...customConfig }: HttpConfig = {}
) => {
  let config: RequestInit = {
    method: "GET",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": data ? "application/json" : "",
    },
    ...customConfig,
  };
  if (config.method?.toUpperCase() === "GET") {
    endPoint += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }

  return fetch(`${apiUrl}/${endPoint}`, config).then(async (response) => {
    // 如果未授权
    if (response.status === 401) {
      auth.logout();
      window.location.reload();
      return Promise.reject();
    }

    const data = await response.json();
    if (response.ok) {
      return data;
    } else {
      return Promise.reject(data);
    }
  });
};

export const useHttp = () => {
  const { user } = useAuth();

  return (...[endPoint, config]: Parameters<typeof http>) =>
    http(endPoint, { ...config, token: user?.token });
};
